// src/utils/rsaUtil.ts
import { JSEncrypt } from 'jsencrypt';

export function RSADecrypt() {}

interface KeyPair {
  privateKey: string;
  publicKey: string;
}

interface RsaUtil {
  bits: number;
  thisKeyPair: JSEncrypt;

  genKeyPair(bits?: number): KeyPair;

  encrypt(plaintext: string | object, publicKey?: string): string;

  decrypt(ciphertext: string, privateKey?: string): any;
}

// @ts-ignore
const rsaUtil: RsaUtil = {
  bits: 1024, // RSA 位数，这里要跟后端对应
  // @ts-ignore
  thisKeyPair: new JSEncrypt({ default_key_size: 1024 }),
  // @ts-ignore
  genKeyPair: function (bits = this.bits) {
    // @ts-ignore
    this.thisKeyPair = new JSEncrypt({ default_key_size: bits });
    return {
      privateKey: this.thisKeyPair.getPrivateKey(),
      publicKey: this.thisKeyPair.getPublicKey(),
    };
  },
  // @ts-ignore
  encrypt: function (plaintext: string | object, publicKey?: string) {
    if (typeof plaintext === 'object') {
      plaintext = JSON.stringify(plaintext);
    }
    if (publicKey) {
      this.thisKeyPair.setPublicKey(publicKey);
    }
    return this.thisKeyPair.encrypt(plaintext);
  },

  decrypt: function (ciphertext: string, privateKey?: string) {
    if (privateKey) {
      this.thisKeyPair.setPrivateKey(privateKey);
    }
    const decString = this.thisKeyPair.decrypt(ciphertext);
    // @ts-ignore
    if (decString.charAt(0) === '{' || decString.charAt(0) === '[') {
      // @ts-ignore
      return JSON.parse(decString);
    }
    return decString;
  },
};

// @ts-ignore
export default rsaUtil;
